import requests
from bs4 import BeautifulSoup

# 获取网页源码
url = 'https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx'

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
# 获取__VIEWSTATE: 9LB7Tan70JFV170bEF2PGiB96/28TKsB7Wjs9qfT1upKTB8Ddc7FDN2883S31xGNlVJrpjzJQxshsriqwXG84EuQzssAnIGu87RHhmRr5AKMixAddbzKMPjsZw4M1ZmVKWz3nCzXO5Z9IuUXyiLxMXZvIO0=
# __VIEWSTATEGENERATOR: C93BE1AE
soup = BeautifulSoup(response.text, 'lxml')
viewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')
viewstate_generator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')


#验证码
code=soup.select('#imgCode')[0].attrs.get('src')

code_url='https://www.gushiwen.cn'+code
#有坑 重新构造请求的话
# import  urllib.request
# urllib.request.urlretrieve(code_url, 'code.png')
#通过session返回值使得请求是一个对象
session = requests.session()
response_code = session.get(code_url, headers=headers)
print(code_url)
with open('code.jpg','wb') as f:
    f.write(response_code.content)
#点击登录
login_url='https://www.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fwww.gushiwen.cn%2fuser%2fcollect.aspx'

code_value=input('请输入验证码：')
data = {
    '__VIEWSTATEGENERATOR': viewstate_generator,
    '__VIEWSTATE': viewstate,
    'from': 'http://www.gushiwen.cn/user/collect.aspx',
    'email': '2854581822@qq.com',
    'pwd': '1593180199AAaa',
    'code': code_value,
    'denglu': '登录'

}
post_content = session.post(login_url, data=data, headers=headers)
with open('gushiwen.html', 'w',encoding='utf-8') as f:
    f.write(post_content.text)
